﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.IO; // Added for file operations

namespace Zzj.Utils
{
    /// <summary>
    /// 精伦身份证IC卡读卡器
    /// </summary>
    internal class JLIDcardread
    {
        // 原有的API声明 - 这些是确定存在的
        [DllImport("Dll/Jldll/Sdtapi.dll")]
        private static extern int InitComm(int iPort);

        [DllImport("Dll/Jldll/Sdtapi.dll")]
        private static extern int Authenticate();

        [DllImport("Dll/Jldll/Sdtapi.dll")]
        private static extern int ReadBaseInfos(StringBuilder Name, StringBuilder Gender, StringBuilder Folk,
                                                    StringBuilder BirthDay, StringBuilder Code, StringBuilder Address,
                                                        StringBuilder Agency, StringBuilder ExpireStart, StringBuilder ExpireEnd);

        [DllImport("Dll/Jldll/Sdtapi.dll")]
        private static extern int CloseComm();

        [DllImport("Dll/Jldll/Sdtapi.dll")]
        private static extern int ReadBaseMsg(byte[] pMsg, ref int len);

        [DllImport("Dll/Jldll/Sdtapi.dll", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall)]
        public static extern int ReadIINSNDN(StringBuilder pMsg);//读物理卡号

        [DllImport("Dll/Jldll/Sdtapi.dll")]
        private static extern int ReadBaseMsgW(byte[] pMsg, ref int len);

        [DllImport("Dll/Jldll/Sdtapi.dll")]
        public static extern int Routon_IC_HL_ReadCardSN(StringBuilder SN);//读取IC卡号

        // 可选的新增API声明 - 使用try-catch包装，避免DLL入口点错误
        private static bool TryImportSDT_ReadIINSNDN(int iPortID, byte[] pucIINSNDN, int iIfOpen, out int result)
        {
            try
            {
                result = SDT_ReadIINSNDN_Internal(iPortID, pucIINSNDN, iIfOpen);
                return true;
            }
            catch
            {
                result = -1;
                return false;
            }
        }

        [DllImport("Dll/Jldll/Sdtapi.dll", EntryPoint = "SDT_ReadIINSNDN", SetLastError = true)]
        private static extern int SDT_ReadIINSNDN_Internal(int iPortID, byte[] pucIINSNDN, int iIfOpen);

        private static bool TryImportRouton_ReadIINSNDN(StringBuilder pMsg, out int result)
        {
            try
            {
                result = Routon_ReadIINSNDN_Internal(pMsg);
                return true;
            }
            catch
            {
                result = -1;
                return false;
            }
        }

        [DllImport("Dll/Jldll/Sdtapi.dll", EntryPoint = "Routon_ReadIINSNDN", SetLastError = true)]
        private static extern int Routon_ReadIINSNDN_Internal(StringBuilder pMsg);

        public static int Opendevice()
        {
            //打开端口
            int intOpenRet = InitComm(1001);//1成功
            return intOpenRet;
        }

        public static int CardAuthentication()//读卡认证
        {
            int intReadRet = Authenticate();
            return intReadRet;
        }

        /// <summary>
        /// 读取身份证基本信息（原有功能）
        /// </summary>
        /// <returns> 身份证信息 </returns>
        public static JLCardInfo ReadIDcard()
        {
            JLCardInfo newCard = null;
            StringBuilder Name = new StringBuilder(31);
            StringBuilder Gender = new StringBuilder(3);
            StringBuilder Folk = new StringBuilder(10);
            StringBuilder BirthDay = new StringBuilder(9);
            StringBuilder Code = new StringBuilder(19);
            StringBuilder Address = new StringBuilder(71);
            StringBuilder Agency = new StringBuilder(31);
            StringBuilder ExpireStart = new StringBuilder(9);
            StringBuilder ExpireEnd = new StringBuilder(9);
            StringBuilder driverMacCard = new StringBuilder(16);
            byte[] pMsg = new byte[256];
            int len = 0;
            string[] temp;
            string[] baseinfo = new string[9];
            char[] param = { '\0' };
            int intReadBaseInfosRet = ReadBaseInfos(Name, Gender, Folk, BirthDay, Code, Address, Agency, ExpireStart, ExpireEnd);
            if (intReadBaseInfosRet != 1)
            {
           
                return newCard;
            }
            else
            {
                newCard = new JLCardInfo();
                newCard.CardNo = Code.ToString();
                newCard.Name = Name.ToString();
                newCard.Sex = Gender.ToString();
                newCard.Birthday = BirthDay.ToString();
                newCard.Address = Address.ToString();
                newCard.Department = Agency.ToString();
                newCard.StartDate = ExpireStart.ToString();
                newCard.EndDate = ExpireEnd.ToString();
                newCard.Nation = Folk.ToString();

                // 读取IC卡号
                int code = ReadIINSNDN(driverMacCard);
                if (code == 1)
                {
                    newCard.driverMacCard = driverMacCard.ToString();
                }
                else
                {
                    newCard.driverMacCard = "读取失败";
                }
                return newCard;
            }
        }

        /// <summary>
        /// 读取身份证信息（增强版，包含更多信息）
        /// </summary>
        /// <returns> 身份证信息 </returns>
        public static JLCardInfo ReadIDcardEnhanced()
        {
            CardAuthentication();

            JLCardInfo newCard = null;
            StringBuilder Name = new StringBuilder(31);
            StringBuilder Gender = new StringBuilder(3);
            StringBuilder Folk = new StringBuilder(10);
            StringBuilder BirthDay = new StringBuilder(9);
            StringBuilder Code = new StringBuilder(19);
            StringBuilder Address = new StringBuilder(71);
            StringBuilder Agency = new StringBuilder(31);
            StringBuilder ExpireStart = new StringBuilder(9);
            StringBuilder ExpireEnd = new StringBuilder(9);

            int intReadBaseInfosRet = ReadBaseInfos(Name, Gender, Folk, BirthDay, Code, Address, Agency, ExpireStart, ExpireEnd);
            if (intReadBaseInfosRet != 1)
            {
                return newCard;
            }
            else
            {
                newCard = new JLCardInfo();
                newCard.CardNo = Code.ToString();
                newCard.Name = Name.ToString();
                newCard.Sex = Gender.ToString();
                newCard.Birthday = BirthDay.ToString();
                newCard.Address = Address.ToString();
                newCard.Department = Agency.ToString();
                newCard.StartDate = ExpireStart.ToString();
                newCard.EndDate = ExpireEnd.ToString();
                newCard.Nation = Folk.ToString();

                // 尝试多种方式读取IC卡号 newCard.driverMacCard = ReadICCardNumber();

                return newCard;
            }
        }

        /// <summary>
        /// 读取IC卡号（多种方式，安全版本）
        /// </summary>
        /// <returns> IC卡号 </returns>
        public static string ReadICCardNumber()
        {
            string icCardNumber = "";

            try
            {
                // 方式1：使用ReadIINSNDN（确定存在）
                StringBuilder driverMacCard = new StringBuilder(16);
                int code1 = ReadIINSNDN(driverMacCard);
                if (code1 == 1)
                {
                    icCardNumber = driverMacCard.ToString();
                    if (!string.IsNullOrEmpty(icCardNumber))
                    {
                        return icCardNumber;
                    }
                }

                // 方式2：尝试使用Routon_ReadIINSNDN（可选）
                StringBuilder routonCard = new StringBuilder(32);
                int code2;
                if (TryImportRouton_ReadIINSNDN(routonCard, out code2) && code2 == 1)
                {
                    icCardNumber = routonCard.ToString();
                    if (!string.IsNullOrEmpty(icCardNumber))
                    {
                        return icCardNumber;
                    }
                }

                // 方式3：尝试使用SDT_ReadIINSNDN（可选）
                byte[] pucIINSNDN = new byte[32];
                int code3;
                if (TryImportSDT_ReadIINSNDN(1001, pucIINSNDN, 0, out code3) && code3 == 1)
                {
                    icCardNumber = Encoding.ASCII.GetString(pucIINSNDN).Trim('\0');
                    if (!string.IsNullOrEmpty(icCardNumber))
                    {
                        return icCardNumber;
                    }
                }

                return "读取失败";
            }
            catch (Exception ex)
            {
                return $"读取异常: {ex.Message}";
            }
        }

        public static int closeID()
        {
            int code = CloseComm();
            return code;
        }
    }

    /// <summary>
    /// IC卡信息类
    /// </summary>
    public class ICCardInfo
    {
        /// <summary>
        /// IC卡号
        /// </summary>
        public string CardNumber { get; set; } = "";

        /// <summary>
        /// 是否读取成功
        /// </summary>
        public bool ReadSuccess { get; set; } = false;

        /// <summary>
        /// 是否有效
        /// </summary>
        public bool IsValid { get; set; } = false;

        /// <summary>
        /// 原始数据
        /// </summary>
        public string RawData { get; set; } = "";

        /// <summary>
        /// 错误信息
        /// </summary>
        public string ErrorMessage { get; set; } = "";

        /// <summary>
        /// 读取时间
        /// </summary>
        public DateTime ReadTime { get; set; } = DateTime.Now;
    }

    public class JLCardInfo
    {
        /// <summary>
        /// 身份证号码
        /// </summary>
        public string CardNo;

        /// <summary>
        /// 身份证物理卡号
        /// </summary>
        public string driverMacCard;

        /// <summary>
        /// 姓名
        /// </summary>
        public string Name;

        /// <summary>
        /// 性别
        /// </summary>
        public string Sex;

        /// <summary>
        /// 出生日期
        /// </summary>
        public string Birthday;

        /// <summary>
        /// 地址
        /// </summary>
        public string Address;

        /// <summary>
        /// 追加地址
        /// </summary>
        public string AddressEx;

        /// <summary>
        /// 发卡机关
        /// </summary>
        public string Department;

        /// <summary>
        /// 证件开始日期
        /// </summary>
        public string StartDate;

        /// <summary>
        /// 证件结束日期
        /// </summary>
        public string EndDate;

        /// <summary>
        /// 民族
        /// </summary>
        public string Nation;

        /// <summary>
        /// 相片路径
        /// </summary>
        public string PhotoPath;

        /// <summary>
        /// 相片的字节信息
        /// </summary>
        public byte[] ArrPhotoByte;

        /// <summary>
        /// 时时图片字节信息
        /// </summary>
        public byte[] PhoTimeByte;
    }
}